# 相关库
from scipy import  stats
from statsmodels.graphics.tsaplots import plot_pacf as PACF   #偏自相关图
from statsmodels.tsa.ar_model import AutoReg
import statsmodels.api as sm  # 统计相关的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import arch  # 条件异方差模型相关的库
import seaborn as sns     #seaborn画出的图更好看，且代码更简单
sns.set(color_codes=True) #seaborn设置背景

#①导入数据
data=pd.read_excel('中芯国际股价数据.xlsx')
data.set_index('date', inplace=True) #设定日期为索引
r2=np.log(data['close'])-np.log(data['close'].shift(1)) #计算对数收益率
r2=r2.dropna()

r=r2
r2=pd.DataFrame(r)
r2.columns=(['return'])

print(r2)
r2.plot(figsize=(12,4))
plt.show()

#②平稳性检验
print("平稳性检验：")
t = sm.tsa.stattools.adfuller(r2)  # ADF检验
print("p-value:   ",t[1])

#③定阶
print("PACF定阶：")
fig = PACF(r2,lags = 30) #使用对数收益率序列
plt.show()

#④AR建模
print("AR建模：")
temp = np.array(r2) # 载入收益率序列
model =AutoReg(temp,lags=5)  
res = model.fit()  
out = 'AIC: {0:0.3f}, HQIC: {1:0.3f}, BIC: {2:0.3f}'
print(out.format(res.aic, res.hqic, res.bic))
print(res.summary())
plt.rcParams['font.sans-serif'] = ['simhei'] #字体为黑体
plt.rcParams['axes.unicode_minus'] = False #正常显示负号 
plt.figure(figsize=(10,4))
plt.plot(temp,'b',label='对数收益率')
plt.plot(res.fittedvalues, 'r',label='AR model')
plt.legend()

#⑤ARCH效应检验
print("计算残差和残差平方：")
r2 = r2['return']
at = r2.values[5:] -  res.fittedvalues

at2 = np.square(at)

plt.figure(figsize=(10,6))
plt.subplot(211)
plt.plot(at,label = 'at')
plt.legend()
plt.subplot(212)
plt.plot(at2,label='at^2')
plt.legend(loc=0)
plt.show()

print("对残差平方序列进行混成检验：原假设为序列没有相关性")
m = 12 # 我们检验12个自相关系数
acf,q,p = sm.tsa.acf(at2,nlags=m,qstat=True)  ## 计算自相关系数 及p-value
out = np.c_[range(1,13), acf[1:], q, p]
output=pd.DataFrame(out, columns=['lag', "AC", "Q", "P-value"])
output = output.set_index('lag')
print(output)



